package com.cloudcross.ssp.web.operator.main;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloudcross.ssp.base.utils.freemarker.FreemarkerTemplateProcessor;
import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.common.consts.Status;
import com.cloudcross.ssp.common.utils.LangUtil;
import com.cloudcross.ssp.common.utils.Md5Tool;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.model.Account;
import com.cloudcross.ssp.model.AccountResources;
import com.cloudcross.ssp.model.Resources;
import com.cloudcross.ssp.model.UserLogin;
import com.cloudcross.ssp.service.IAccountService;
import com.cloudcross.ssp.service.IOperatorService;
import com.cloudcross.ssp.service.IResourcesService;
import com.cloudcross.ssp.service.IUserLoginService;

/**
 * 权限管理 修改人：wuqiang.du 修改时间：2016-03-14 修改内容：添加注释 运营商权限管理，运营商管理员（后台系统创建）登入系统后
 */
@Controller("operator.AuthorityController")
@RequestMapping("/operator/main/authority")
public class AuthorityController extends SimpleController {

    @Autowired
    private FreemarkerTemplateProcessor templateProcessor;

    @Autowired
    protected IAccountService           accountService;

    @Autowired
    protected IUserLoginService         userLoginService;

    @Autowired
    protected IOperatorService          operatorService;

    @Autowired
    protected IResourcesService         resourcesService;

    /**
     * 重定向
     * 
     * @return 目标url
     */
    @RequestMapping
    public String index() {
        return redirect(page("list"));
    }

    /**
     * 媒体端权限管理(媒体账户给自己创建小账号 )
     * 
     * @param model
     * @param page
     * @param searchValue
     * @return 查询条件：sys_type = 2 且不是当前登录用户,当前登录用户的operatorId
     */
    @RequestMapping("list")
    public String list(Model model, @RequestParam(defaultValue = "1") int page, String searchValue) {
        Map<String, Object> condition = new HashMap<String, Object>();

        condition.put("sysType", 2);//运营商系统sys_type = 2
        //处理查询条件
        if (searchValue != null && searchValue != "") {
            condition.put("searchVal", "%" + searchValue + "%");
            model.addAttribute("searchValue", searchValue);
        }
        //当前登录用户
        Account loginAccount = getLoginUser();
        condition.put("accountId", loginAccount.getId());
        condition.put("operatorId", loginAccount.getOperatorId());
        int totalRow = this.accountService.queryAccountCountByCondition(condition);
        Pager pager = new Pager();
        pager.setPage(page);
        pager.setTotalRow(totalRow);
        List<Account> accountList = accountService.queryAccountByCondition(condition, pager);
        //循环获取查询到账号的登录时间；保存到对象的creatTime字段中
        for (int i = 0; i < accountList.size(); i++) {
            UserLogin login = userLoginService.queryUserLoginById(accountList.get(i).getId());
            //查询到的用户可能从未登录过系统，所以这里要判断一下，避免空指针异常！
            if (login == null) {
                continue;
            }
            accountList.get(i).setCreateTime(login.getLoginTime());
        }
        model.addAttribute("accountList", accountList);
        model.addAttribute("pager", pager);
        return page("list");
    }

    /**
     * 媒体创建小账号页面
     * 
     * @return
     */
    @RequestMapping("/create")
    public String create(Model model) {
        Account account = getLoginUser();
        List<Resources> parentResList = resourcesService.findAllResourcesByAccountId(account.getId());
        model.addAttribute("parentResList", parentResList);
        return page("create");
    }

    /**
     * 媒体编辑页面
     * 
     * @param model
     * @param accountId
     * @return 数据：1.选择账号的信息 2.选中账号的权限信息
     */
    @RequestMapping("/edit")
    public String edit(Model model, @RequestParam long accountId) {
        //当前登录用户信息
        Account account = accountService.queryAccountById(accountId);

        //当前账号的权限信息
        String authority = "";
        List<AccountResources> resources = resourcesService.queryResourcesByAccountId(accountId);
        //查询resourceId，拼接字符长，逗号分隔（a1,a2,...,an）
        if (resources.size() > 0) {//resources<=0说明没有添加权限信息
            for (int i = 0; i < resources.size() - 1; i++) {
                //循环取出resources中的id
                authority = authority + resources.get(i).getResourceId().toString() + ",";
            }
            authority = authority + resources.get(resources.size() - 1).getResourceId().toString();
        }

        Account parentAcc = getLoginUser();
        List<Resources> parentResList = resourcesService.findAllResourcesByAccountId(parentAcc.getId());
        model.addAttribute("parentResList", parentResList);
        model.addAttribute("authority", authority);
        model.addAttribute("account", account);
        return page("edit");
    }

    /**
     * 媒体权限管理保存方法
     * 
     * @param model
     * @param t
     * @param authority
     * @param ensurePassword
     * @return 创建小账号，不用创建媒体
     */
    @RequestMapping("/save")
    public String save(Model model, @ModelAttribute("form") Account t,
                       @RequestParam(value = "authority", defaultValue = "") String authority,
                       @RequestParam(value = "ensurePassword", defaultValue = "") String ensurePassword) {
        Account acc = new Account();
        Account account = getLoginUser();
        String password = t.getPassword();
        if ((t.getId()) == 0) {//新建媒体小账号
            acc.setAccountName(t.getAccountName());
            acc.setPassword(Md5Tool.getMd5(password));
            acc.setRealName(t.getRealName());
            acc.setSysType(2);//系统类型
            acc.setDescription(account.getDescription() + "（小）");
            acc.setType(2);//账号类型（2）
            acc.setTel(t.getTel());
            acc.setCreateTime(new Date());
            acc.setState(t.getState());
            acc.setOperatorId(account.getOperatorId());
            accountService.insertAccount(acc);
            //处理权限
            if (authority != null && !authority.equals("")) {
                List<Long> autList = new ArrayList<Long>();
                String[] aut = authority.split(",");
                for (int i = 0; i < aut.length; i++) {
                    autList.add(Long.parseLong(aut[i]));
                }
                resourcesService.addAccountResourcess(acc.getId(), autList);
            }
        } else {//修改保存
            if (StringUtils.isNotBlank(password)) {
                acc.setPassword(Md5Tool.getMd5(password));
            }
            acc.setId(t.getId());
            acc.setRealName(t.getRealName());
            acc.setTel(t.getTel());
            acc.setState(t.getState());
            accountService.updateAccount(acc);
            //处理权限
            if (authority != null && !authority.equals("")) {
                List<Long> autList = new ArrayList<Long>();
                String[] aut = authority.split(",");
                for (int i = 0; i < aut.length; i++) {
                    autList.add(Long.parseLong(aut[i]));
                }
                resourcesService.addAccountResourcess(acc.getId(), autList);
            }
        }
        // 跳转到管理页面。
        return redirect(page("list"));
    }

    /**
     * 开启 权限管理：1（开启），0（停止） disable(1), enable(0),
     * 
     * @param id
     * @return
     */
    @RequestMapping("enable")
    @ResponseBody
    public String enable(Long[] id) {
        if (ArrayUtils.isNotEmpty(id)) {
            accountService.updateState(LangUtil.array2List(id), Status.disable.value);
        }
        return OK;
    }

    /**
     * 暂停 权限管理：1（开启），0（停止） disable(1), enable(0),
     * 
     * @param id
     * @return
     */
    @RequestMapping("disable")
    @ResponseBody
    public String disable(Long[] id) {
        if (ArrayUtils.isNotEmpty(id)) {
            accountService.updateState(LangUtil.array2List(id), Status.enable.value);
        }
        return OK;
    }

    /**
     * 跳转到个人信息修改页面
     * 
     * @param model
     * @return
     */
    @RequestMapping("loginperson")
    public String personInfEdit(Model model) {
        Account account = getLoginUser();
        model.addAttribute("account", account);
        return page("loginperson");
    }

    /**
     * 个人信息修改的保存操作
     * 
     * @param model
     * @param t
     * @param ensurePassword
     * @return 修改密码（不管密码与原始密码是否相同），重新登录；不修改密码，调到主页
     */
    @RequestMapping("/saveloginperson")
    public String saveloginperson(Model model, @ModelAttribute("form") Account t,
                                  @RequestParam(value = "ensurePassword", defaultValue = "") String ensurePassword) {
        Account acc = new Account();
        String password = t.getPassword();
        acc.setId(t.getId());
        if (StringUtils.isNotBlank(password)) {
            acc.setPassword(Md5Tool.getMd5(password));
        }
        acc.setRealName(t.getRealName());
        acc.setTel(t.getTel());
        acc.setState(t.getState());

        accountService.updateAccount(acc);
        if (StringUtils.isNotBlank(password)) {
            return "/login";//修改密码跳转login界面重新登陆
        } else {
            return "/back/main/dashboard";//并未修改密码，则跳转主页！
        }
    }

    @RequestMapping("isExist")
    @ResponseBody
    public String isExist(Model model, @RequestParam(defaultValue = "") String accountName) {
        String success = "";
        Account account = accountService.querySingleAccount(accountName);
        if (account != null) {
            model.addAttribute("isExist", new Long(1));
            success = "YES";
        } else {
            model.addAttribute("isExist", new Long(0));
            success = "NO";
        }
        return success;
    }

    /**
     * 账号信息导出
     * 
     * @param response
     * @param searchValue
     */
    @RequestMapping("/exportDataReportExcel")
    public void exportDataReportExcel(HttpServletResponse response, String searchValue) {
        Map<String, Object> condition = new HashMap<String, Object>();//存放查询条件
        condition.put("sysType", 2);//运营商系统sys_type = 2
        //处理查询条件
        String value = "";
        if (StringUtils.isNotBlank(searchValue)) {
            try {
                value = new String(searchValue.trim().getBytes("ISO-8859-1"), "UTF-8");
                condition.put("searchVal", "%" + value + "%");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        //根据当前登录用户获取代理商ID
        Account loginAccount = getLoginUser();
        condition.put("accountId", loginAccount.getId());

        List<Account> accountList = accountService.queryAccountByCondition(condition, null);
        for (int i = 0; i < accountList.size(); i++) {
            UserLogin login = userLoginService.queryUserLoginById(accountList.get(i).getId());
            //对于没有登过系统的账号，显示创建时间
            if (login == null) {
                continue;
            }
            accountList.get(i).setCreateTime(login.getLoginTime());
        }
        condition.put("dataList", accountList);

        response.reset();
        // Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8
        response.setContentType("application/vnd.ms-excel;charset=utf8");
        // 设置excel文件名称
        SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "account" + df2.format(new Date());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        // 需要对excel的列和行的总数进行指定
        int column = 7;
        condition.put("dataSize", (accountList.size() + 100));
        condition.put("column", column);

        condition.put("accountList", "账号列表");
        String excelTemplate = templateProcessor.processTemplate("excel/dataAccount.ftl", condition);
        try {
            PrintWriter out = response.getWriter();
            out.write(excelTemplate);
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
